import uvicorn as u
import datetime
from fastapi import FastAPI, Form
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates

from client import FilePipe, PHOTOS


filepipe = FilePipe()

app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
templates = Jinja2Templates(directory='templates')


def get_photos():
    photos = []
    for p in PHOTOS.glob('**/*'):
        weight, date, cellphone = p.stem.split('_')
        date = datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
        photos.append({
            'path': f'static/photos/{p.name}',
            'cellphone': cellphone,
            'weight': int(weight),
            'date': date.strftime('%Y-%m-%d %H:%M:%S')
        })
    return photos

@app.get('/')
async def index(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

@app.get('/put')
async def put(request: Request):
    return templates.TemplateResponse('put.html', {'request': request})

@app.get('/api/put/{cellphone}')
async def api_put(cellphone):
    filepipe.put(cellphone)
    return True

@app.get('/take_off')
async def api_take_off():
    filepipe.set({'action': 'wait'})
    return "取出模式已关闭！"

@app.get('/show')
async def show(request: Request):
    filepipe.set({'action': 'take'})
    return templates.TemplateResponse('show.html', {'request': request})

# image name format: weight_date_cellphone.jpg sample: 125_20210501122311_13012341234.jpg
@app.get('/api/show')
async def api_show():
    photos = get_photos()
    dweight = filepipe.get_last_weight()
    photos.sort(key=lambda x: abs(x['weight'] - dweight))
    return photos


if __name__ == '__main__':
    u.run(app, host='0.0.0.0', port=80)

